package com.ruoyi.controller.jpjs.budget;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.jpjs.common.budget.Basicprice;
import com.ruoyi.domain.jpjs.common.budget.Details;
import com.ruoyi.domain.jpjs.common.budget.Planbudget;
import com.ruoyi.domain.jpjs.common.budget.PlanbudgetParam;
import com.ruoyi.service.jpjs.budget.BudgetPlanService;
import com.ruoyi.service.jpjs.concrete.ConcreteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/planbudget")
public class BudgetPlanController extends BaseController {

    private String prefix = "jpjs/planbudget";

    @Autowired
    private BudgetPlanService budgetPlanService;

    @Autowired
    private ConcreteService concreteService;

    /**
     * 跳转分页页面
     */
    @GetMapping()
    public String view() {
        return prefix + "/list";
    }

    @PostMapping("/basicList")
    @ResponseBody
    public TableDataInfo basicList(@RequestParam Map<String, Object> map) {
        startPage();
        List<Basicprice> list = budgetPlanService.queryBasicPriceList(map);
        List<Planbudget> budgetList = budgetPlanService.queryBudgetList(map);
        List<Details> detailList = budgetPlanService.queryDetailsList(map);

        String prePrice = "0";
        String accFinish = "0";

        if(StringUtils.isNotEmpty(budgetList)){
             prePrice = budgetList.get(0).getPrePrice();
        }
        if(StringUtils.isNotEmpty(detailList)){
            accFinish = detailList.get(0).getAccFinish();
        }

        if(StringUtils.isNotEmpty(list)){
            // 累计已完成
            list.get(0).setAccFinishPrice(String.valueOf(Double.valueOf(prePrice) + Double.valueOf(accFinish)));
            list.get(0).setCountOffset(getPercentage(Double.valueOf(list.get(0).getPreSettlePrice()), Double.valueOf(list.get(0).getAccFinishPrice())));
        }
        return getDataTable(list);
    }

    @PostMapping("/budgeList")
    @ResponseBody
    public TableDataInfo budgeList(@RequestParam Map<String, Object> map) {
        startPage();
        List<Planbudget> list = budgetPlanService.queryBudgetList(map);
        return getDataTable(list);
    }

    @PostMapping("/detailList")
    @ResponseBody
    public TableDataInfo detailList(@RequestParam Map<String, Object> map) {
        startPage();
        List<Details> list = budgetPlanService.queryDetailsList(map);
        List<Planbudget> budgetList = budgetPlanService.queryBudgetList(map);
        queryFirstForward(list, budgetList);


        return getDataTable(list);
    }

    /**
     * 查询一季度结转
     * @param list
     * @param budgetList
     */
    private void queryFirstForward(List<Details> list, List<Planbudget> budgetList) {
        // 第一季度计划 - 第一季度完成  =一季度结转
        // 计划
        double plan = 0;
        double finish = 0;
        if(StringUtils.isNotEmpty(budgetList)){
            for(Planbudget planbudget : budgetList){
                if(planbudget.getType().equals("1")){
                    if(StringUtils.isNotEmpty(planbudget.getJanValue())){
                        plan = plan + Double.valueOf(planbudget.getJanValue());
                    }
                    if(StringUtils.isNotEmpty(planbudget.getFebValue())){
                        plan = plan + Double.valueOf(planbudget.getFebValue());
                    }
                    if(StringUtils.isNotEmpty(planbudget.getMarValue())){
                        plan = plan + Double.valueOf(planbudget.getMarValue());
                    }
                }
            }
        }

        // 计划
        if(StringUtils.isNotEmpty(list)){
            // 完成
            if(StringUtils.isNotEmpty(list.get(0).getJanFinish())){
                finish = finish + Double.valueOf(list.get(0).getJanFinish());
            }
            if(StringUtils.isNotEmpty(list.get(0).getFebFinish())){
                finish = finish + Double.valueOf(list.get(0).getFebFinish());
            }
            if(StringUtils.isNotEmpty(list.get(0).getMarFinish())){
                finish = finish + Double.valueOf(list.get(0).getMarFinish());
            }
            list.get(0).setFirstForward(String.valueOf(plan-finish));
        }
    }

    @GetMapping("/addBasic")
    public String addProject(ModelMap mmp, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        return prefix + "/addBasic";
    }

    @GetMapping("/addBudget")
    public String addBudget(ModelMap mmp, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        return prefix + "/addBudget";
    }

    @GetMapping("/addDetails")
    public String addDetails(ModelMap mmp, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        return prefix + "/addDetails";
    }

    @PostMapping("/saveBasic")
    @ResponseBody
    public AjaxResult saveBasic(Basicprice basicprice) {
        String programCode = null;

        String patternStr;
        String companyStr = null;

        String bidTime = basicprice.getBidTime();
        String bidStr= bidTime.replaceAll("-", "").substring(2, 6);

        String pattern = basicprice.getPattern();
        if(pattern.equals("0")){
            patternStr = "N";
        }else{
            patternStr = "W";
        }

        // 根据工程公司ID获取工程公司名称
        String companyName = budgetPlanService.queryCompanyNameById(basicprice.getCompanyId());
        if(companyName.contains("第一")){
            companyStr = "D1";
        }
        if(companyName.contains("第二")){
            companyStr = "D2";
        }
        if(companyName.contains("第三")){
            companyStr = "D3";
        }
        if(companyName.contains("第四")){
            companyStr = "D4";
        }
        if(companyName.contains("第五")){
            companyStr = "D5";
        }

        System.out.println((int)((Math.random()*9+1)*100));
        String randomStr = String.valueOf((int)((Math.random()*9+1)*100));

        programCode = bidStr + patternStr + companyStr + randomStr;
        basicprice.setProgramCode(programCode);

        return toAjax(budgetPlanService.insertBasicPrice(basicprice));
    }

    @PostMapping("/savePlanbudget")
    @ResponseBody
    public AjaxResult savePlanbudget(PlanbudgetParam planbudgetParam) {
        // 前期产值+全年完成产值=累计已完成
//        if(StringUtils.isNotEmpty(planbudget.getPrePrice()) || StringUtils.isNotEmpty(planbudget.getAccFinish())){
//            Basicprice basicprice = new Basicprice();
//            basicprice.setAccFinishPrice(String.valueOf(Double.valueOf(planbudget.getPrePrice()) + Double.valueOf(planbudget.getAccFinish())));
//            basicprice.setProgramId(planbudget.getProgramId());
//            budgetPlanService.updateBasicPriceFinish(basicprice);
//        }
        List<Planbudget> planbudget = planbudgetParam.getPlanbudgetParam();
        for (Planbudget budget : planbudget) {
            budget.setJanValue(budget.getJanValue());
            budget.setFebValue(budget.getFebValue());
            budget.setMarValue(budget.getMarValue());
            budget.setAprValue(budget.getAprValue());
            budget.setMayValue(budget.getMayValue());
            budget.setJunValue(budget.getJunValue());
            budget.setJulValue(budget.getJulValue());
            budget.setAugValue(budget.getAugValue());
            budget.setSepValue(budget.getSepValue());
            budget.setOctValue(budget.getOctValue());
            budget.setNovValue(budget.getNovValue());
            budget.setDecValue(budget.getDecValue());

            budget.setCompanyId(planbudgetParam.getCompanyId());
            budget.setProgramId(planbudgetParam.getProgramId());
            budget.setPrePrice(planbudgetParam.getPrePrice());
            budget.setPoorQuality(planbudgetParam.getPoorQuality());
        }

        return toAjax(budgetPlanService.insertPlanBudgetBatches(planbudget));
    }

    @PostMapping("/saveDetails")
    @ResponseBody
    public AjaxResult saveDetails(Details details) {
        return toAjax(budgetPlanService.insertDetails(details));
    }

    @PostMapping("/queryBasicByProgramId")
    @ResponseBody
    public List<Basicprice> queryBasicByProgramId(@RequestParam Map<String, Object> map) {
        return budgetPlanService.queryBasicPriceList(map);
    }

    @PostMapping("/queryBudgeByProgramId")
    @ResponseBody
    public List<Planbudget> queryBudgeByProgramId(@RequestParam Map<String, Object> map) {
        return budgetPlanService.queryBudgetList(map);
    }

    @PostMapping("/queryDetailsByProgramId")
    @ResponseBody
    public List<Details> queryDetailsByProgramId(@RequestParam Map<String, Object> map) {
        return budgetPlanService.queryDetailsList(map);
    }

    @GetMapping("/editBasicView")
    public String addProject(ModelMap mmp,String programId) {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        mmp.put("basic", budgetPlanService.queryBasicPriceList(map).get(0));
        mmp.put("programId", programId);
        return prefix + "/editBasic";
    }

    @GetMapping("/editBudgetView")
    public String editBudgetView(ModelMap mmp,String programId) {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        mmp.put("budget", budgetPlanService.queryBudgetList(map).get(0));
        mmp.put("programId", programId);
        return prefix + "/editBudget";
    }

    @GetMapping("/editDetailView")
    public String editDetailView(ModelMap mmp,String programId) {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        mmp.put("detail", budgetPlanService.queryDetailsList(map).get(0));
        mmp.put("programId", programId);
        return prefix + "/editDetails";
    }

    @PostMapping("/editBasic")
    @ResponseBody
    public AjaxResult editBasic(Basicprice basicprice) {
        return toAjax(budgetPlanService.updateBasicPrice(basicprice));
    }

    @PostMapping("/editBudget")
    @ResponseBody
    public AjaxResult editBudget(PlanbudgetParam planbudgetParam) {
        List<Planbudget> planbudget = planbudgetParam.getPlanbudgetParam();
        for (Planbudget budget : planbudget) {
            budget.setJanValue(budget.getJanValue());
            budget.setFebValue(budget.getFebValue());
            budget.setMarValue(budget.getMarValue());
            budget.setAprValue(budget.getAprValue());
            budget.setMayValue(budget.getMayValue());
            budget.setJunValue(budget.getJunValue());
            budget.setJulValue(budget.getJulValue());
            budget.setAugValue(budget.getAugValue());
            budget.setSepValue(budget.getSepValue());
            budget.setOctValue(budget.getOctValue());
            budget.setNovValue(budget.getNovValue());
            budget.setDecValue(budget.getDecValue());

            budget.setCompanyId(planbudgetParam.getCompanyId());
            budget.setProgramId(planbudgetParam.getProgramId());
            budget.setPrePrice(planbudgetParam.getPrePrice());
            budget.setPoorQuality(planbudgetParam.getPoorQuality());
        }
        return toAjax(budgetPlanService.updatePlanBudgetBatches(planbudget));
    }

    @PostMapping("/editDetail")
    @ResponseBody
    public AjaxResult editDetail(Details details) {
        return toAjax(budgetPlanService.updateDetails(details));
    }

    @PostMapping("/removeBasic")
    @ResponseBody
    public AjaxResult removeBasic(String ids) {
        try {
            return toAjax(budgetPlanService.deleteBasicPrice(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @PostMapping("/removeBudget")
    @ResponseBody
    public AjaxResult removeBudget(String ids) {
        try {
            return toAjax(budgetPlanService.deletePlanBudget(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @PostMapping("/removeDetails")
    @ResponseBody
    public AjaxResult removeDetails(String ids) {
        try {
            return toAjax(budgetPlanService.deleteQuarterDetails(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @PostMapping("/export")
    @ResponseBody
    public AjaxResult exportBasic(@RequestParam Map<String, Object> map) {
        List<Basicprice> list = budgetPlanService.queryBasicPriceList(map);
        List<Planbudget> budgetList = budgetPlanService.queryBudgetList(map);
        List<Details> detailList = budgetPlanService.queryDetailsList(map);

        // 基本
        if(map.get("typeFlag").toString().equals("0")){
            String prePrice = "0";
            String accFinish = "0";

            if(StringUtils.isNotEmpty(budgetList)){
                prePrice = budgetList.get(0).getPrePrice();
            }
            if(StringUtils.isNotEmpty(detailList)){
                accFinish = detailList.get(0).getAccFinish();
            }

            if(StringUtils.isNotEmpty(list)){
                // 累计已完成
                list.get(0).setAccFinishPrice(String.valueOf(Double.valueOf(prePrice) + Double.valueOf(accFinish)));
                list.get(0).setCountOffset(getPercentage(Double.valueOf(list.get(0).getPreSettlePrice()), Double.valueOf(list.get(0).getAccFinishPrice())));
            }
            ExcelUtil<Basicprice> util = new ExcelUtil<Basicprice>(Basicprice.class);
            return util.exportExcel(list, "进度情况详情");
        }

        // 计划
        if(map.get("typeFlag").toString().equals("1")){
            ExcelUtil<Planbudget> util = new ExcelUtil<Planbudget>(Planbudget.class);
            return util.exportExcel(budgetList, "进度情况详情");
        }

        // 完成
        if(map.get("typeFlag").toString().equals("2")){
            queryFirstForward(detailList, budgetList);
            ExcelUtil<Details> util = new ExcelUtil<Details>(Details.class);
            return util.exportExcel(detailList, "进度情况详情");
        }
        return toAjax(1);
    }

    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        return concreteService.getProgramTree();
    }

    private String getPercentage(double totalNum, double planFinishNum) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        BigDecimal bg = new BigDecimal(Double.valueOf(planFinishNum) / Double.valueOf(totalNum));
        return nt.format(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
    }
}
